package cn.jiyun.service.impl;

import cn.jiyun.mapper.UserMapper;
import cn.jiyun.pojo.User;
import cn.jiyun.service.UserService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public List<User> findAll() {
        String userListStr =(String) redisTemplate.opsForValue().get("user_list");
        ObjectMapper objectMapper = new ObjectMapper();
        List<User> userList=null;
        if (userListStr!=null){

            try {
                userList=objectMapper.readValue(userListStr,List.class);
            } catch (IOException e) {
                e.printStackTrace();
            }

            System.out.println("从redis取值");
        }else {
            System.out.println("从mysql取值");
            //如果不存在，查询数据库，再存入redis
            userList = userMapper.selectList(null);
            //将数据库查询结果转json存入redis
        }

        try {
            String json = objectMapper.writeValueAsString(userList);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        return userList;
    }
}
